package com.ikdong.toodle.util;

import java.util.List;
import org.json.JSONObject;
import android.util.Log;
import com.google.gson.Gson;
import com.ikdong.toodle.exception.TDException;
import com.ikdong.toodle.model.Account;
import com.ikdong.toodle.model.BasicTask;
import com.ikdong.toodle.model.Folder;
import com.ikdong.toodle.model.Goal;
import com.ikdong.toodle.model.Task;
import com.ikdong.toodle.model.TaskContext;

public class JsonUtil {
	public static Gson gson = new Gson();
	
	public static Account parseToAccount(String json){
		return gson.fromJson(json, Account.class);
	}
	
	public static Task parseToTask(String json){
		return gson.fromJson(json, Task.class);
	}
	
	public static String parseTaskToJson(BasicTask task){
		return gson.toJson(task);
	}
	
	public static String parseTaskToJson(List<BasicTask> tasks){
		return gson.toJson(tasks);
	}
	
	public static Folder parseToFolder(String json){
		Folder folder = null;
		try {
			folder = new Folder();
			JSONObject obj = new JSONObject(json);	
			if (!obj.isNull("id"))
				folder.setId(obj.getLong("id"));
			if (!obj.isNull("name"))
				folder.setName(obj.getString("name"));
			if (!obj.isNull("private"))
				folder.setPrivated(obj.getLong("private"));
			if (!obj.isNull("archived"))
				folder.setArchived(obj.getLong("archived"));
			if (!obj.isNull("ord"))
				folder.setOrder(obj.getLong("ord"));
		} catch (Exception e) {
			Log.e(Constant.TAG, "JsonUtil.parseToFolder()", e);
		}
		return folder;
	}
	
	public static TaskContext parseToContext(String json){
		return gson.fromJson(json, TaskContext.class);
	}
	
	public static Goal parseToGoal(String json){
		return gson.fromJson(json, Goal.class);
	}
	
	public static TDException parseError(String json){
		TDException exception = null;
		try{
			JSONObject obj = new JSONObject(json);
			if(obj.has("errorCode")){
				String code = obj.getString("errorCode");
				String message = obj.getString("errorDesc");
				exception = new TDException(code,message);
			}
		}catch(Exception e){
			//Log.e(Constant.TAG, "JsonUtil.isError()", e);
		}
		
		return exception;
	}
}
